<?php
/* 
 *销售详情
 */
class Sale_detailAction extends TransDetailAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
            $map['name'] = array('like',"%".$key."%");//产品名称
            $map['sale_no'] = array('like',"%".$key."%");//销售单号
            $map['tm'] = array('like',"%".$key."%");//条码
            $map['logino'] = array('like',"%".$key."%");
            /* exact filter
            $map['Warehouse.name'] = array('like',"%".$key."%");//仓库
            $map['Customer.name'] = array('like',"%".$key."%");//customer
            $map['number'] = array('eq',$key);
            //$map['minstock'] = array('like',"%".$key."%");*/
            $map['_logic'] = "or";
        }
        if(!empty($_REQUEST['sale_id'])){
           $map['sale_id'] = $_REQUEST['sale_id'];
        }
        if(!empty($_REQUEST['user_id'])){
           $map['user_id'] = $_REQUEST['user_id'];
        }
    }

    public function _before_index(){
        parent::_before_index();
        //$this->assign('customers',getModelField('Customer','id,name','sort'));
        //$this->assign('users',getModelField('User'));
    }
    public function  index() {
        parent::index('Sale_detailView');    
    }

    public function  _before_insert() {
        $pid = $_POST['product_id'];
         if(!$pid)
            $this->error('请选择至少一个产品');
        if($pid != array_unique($pid))
          $this->error('您选择的产品存在重复，请去重后再操作！');

          $number = $_POST['number'];
          foreach ($number as $key => $value) {
            if($value <1 )
              $this->error("产品数量必须大于等于 1 ");
            continue;
          }

        $name=$this->getActionName();
        $parent_name = strtolower( str_replace('_detail', '', $name) );
        if(empty($_POST[$parent_name.'_id']) )
            $this->error("必须选择单号");
    }

   // $no_reutrn 默认为0，则返回操作提示，否则不返回
    //is_gift 是否是赠品。默认为0，非赠品。1为赠品
    public function insert($no_return = 0,$is_gift = 0){
        $data = $_POST;
        $sale = M('Sale')->getById($_POST['sale_id'] );
        $cache_goods = S('goods');

        $small_count = count($data['product_id']);
        $m = 'sale';
        $sale_detail = M('Sale_detail');

        for( $i =0 ; $i<$small_count;$i++) {
           $detail_data= array(
                   $m.'_id'=> $data[$m.'_id'],
                   $m.'_no'=> $data[$m.'_no'],
                   'product_id'=> $data['product_id'][$i],
                   'options'=> $data['options'][$i],
                   'out_number' => empty($data['out_number'][$i]) ? getOut_number($data['product_id'][$i],1 ) : $data['out_number'][$i] , //第三方编码,全部默认取药房网
                   'sale_title' => empty($data['sale_title'][$i]) ? makeSale_title( $data['product_id'][$i]) : $data['sale_title'][$i], 
                   'lot'=> $data['lot'][$i],   //产品批号
                   'exp'=> $data['exp'][$i],   //截止有效期
                   'price'=> $data['price'][$i],
                   'number'=> $data['number'][$i],
                   'customer_id'=> $data['customer_id'],    //冗余设计
                   'is_gift' => $is_gift,
                   'warehouse_id' => $cache_goods[$data['product_id'][$i]]['warehouse_id'],
                   'create_time'=> time(),
           );
           $list = $sale_detail->add($detail_data);
           //TODO 以下部分做成公共的模块
           $warehouse_id = $sale['warehouse_id'];
           //TODO 库存可能不能减少 必须由仓库人员操作才能发货。而仓库人员不操作订单详情
           //TODO 订单完成发货后，不得修改
           //A('Trans')->updateStock($detail_data['product_id'], $warehouse_id, 'out', $detail_data['number'] );
           //如果修改了价格，则同时更新财务记录
            updateTotalPrice('Sale',$list,$detail_data['number'],$detail_data['price']);

            //update sum_number
            updateSumNumber('Sale',$list,$detail_data['number']);

            if($no_return == 0){ //自动增加的，则不记录日志
              /******************日志记录*********************/
               $mod_field = getModelName ($list, "Sale_detail",$field);
              //如果未取到字段值 ，则返回对应的ID编号
              $msg = '新增 Sale_detail: '.$mod_field.' (编号：'.$list.')';
              A('Action')->writeLog($msg,'新增','Sale_detail',$list);
            }
        }
        if($no_return == 0){
            $jumpUrl = $_REQUEST['jumpUrl'];
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
             
          if( $sale['prepare_status'] == 1 || $sale['prepare_status'] == 2 ){
              $sale_id = $_POST['sale_id'];
              $content = "增加了商品,需要重新打印配货单";
              //A('Message')->write_message($sale_id,2,$content,$_SESSION[C('USER_AUTH_KEY')]);
              $this->success('新增成功。<br/><br/><font color="red">该单正在配货中，请通知仓库调整！</font>',false,10);
          }else
            $this->success ('新增成功!');
        }
            
                       
    }

    public function update(){
      //在更新前，先更新下商品编码
      //目前基本全部使用京卫的订单体系
      if(empty($_POST['options']))
          $goods_id = getMyGoodsIdJw($_POST['out_number'],$_POST['sale_title'] );
      
      else //淘宝订单
         $goods_id = getMyGoodsId($_POST['out_number'],$_POST['options'] );
      if($goods_id > 0){
        $cache_goods = S('goods');
        $_POST['product_id'] = $goods_id;
        $_POST['warehouse_id'] = $cache_goods[$goods_id]['warehouse_id']; 
      }
      $sale_id = getModelName($_REQUEST['id'],'Sale_detail','sale_id');
      $sale_pstatus = M('Sale')->where('id = '.$sale_id)->getField('prepare_status');
      if( $sale_pstatus == 1 || $sale_pstatus == 2){
          $this->micro_update();
          $content = "修改了商品的数量或其他内容,需要重新打印配货单";
          //A('Message')->write_message($sale_id,2,$content,$_SESSION[C('USER_AUTH_KEY')]);
          $this->success('修改成功。<br/><br/><font color="red">该单正在配货中，请通知仓库调整！</font>',false,10);
      }else
          parent::update();
    }

    // 防止导入订单的产品数据没有正确编码，重新编码
    public function update_goods()
    {
        $is_tb = $_REQUEST['is_tb'];
        $sale_no= $_REQUEST['sale_no'];
        $sale = M('Sale')->where('sale_no = "'.$sale_no.'"')->find(); 
        $sale_detail = M('Sale_detail');
        $list = $sale_detail->where('sale_no = "'.$sale_no.'"')->findAll();
        if($is_tb == 0 ){
          foreach ($list as $key => $value) {
                $goods_id = getMyGoodsIdJw($value['out_number'],$value['sale_title'] );
                if($goods_id > 0)
                  $sale_detail ->where('id ='.$value['id'])->setField('product_id',$goods_id);
            }
        }else{
          foreach ($list as $key => $value) {
                $goods_id = getMyGoodsId($value['out_number'],$value['options'] );
                if($goods_id > 0)
                  $sale_detail ->where('id ='.$value['id'])->setField('product_id',$goods_id);
            }
        }
            
        $this->assign('jumpUrl','__APP__/Sale/edit/id/'. $sale['id']);
        $this->success('更新商品成功');
    }

  //$gift_lot 赠送几份礼品，默认为1
    public function gift_insert($saleid,$saleno,$gift_id = 0,$gift_lot=1)
    {
      //用于自动增加赠品
      if(!empty($saleid))
        unset($_POST);   //如果是系统自动传入的单号 ，则重置所有的post
      $_POST['sale_id'] = empty($saleid)? $_POST['sale_id'] : $saleid;
      $_POST['sale_no'] = empty($saleno)? $_POST['sale_no'] : $saleno;
      $_POST['customer_id'] = getModelName( $_POST['sale_id'],'Sale','customer_id' );

      $_POST['gift_id'] = empty($gift_id)? $_POST['gift_id'] : $gift_id;
      $condition = array();
      $condition['gift_id'] = $_POST['gift_id'] ; //暂时只接受一个gift_id
      $gift = M('Gift_detail')->where($condition)->findAll();
      foreach ($gift as $key => $value) {
        $_POST['product_id'][$key] = $value['goods_id'];
        $_POST['price'][$key] = $value['price'];
        $_POST['number'][$key] = $value['number']*$gift_lot;
        $_POST['sale_title'][$key] = $value['name'];
      }
      if(!empty($saleid))
        $this->insert(1,1); //通过自动增加赠品的，则不返回操作提示,同时记录为赠品
      else
        $this->insert(0,1);
      
    }

    //通过订单详情ID返回新的可复制的数据，ajax返回
    public function getSaleDetail()
    {
      $sale_detail_id = $_POST['sale_detail_id'];
      $detail = M('Sale_detail')->getById($sale_detail_id);
      if(is_array($detail)){
        $tr_str = '<tr><form action="'.__APP__.'/Sale_detail/copy_detail" method="post">';
          $tr_str .= '<td>-- <input type="hidden" name="sale_id" value="'.$detail['sale_id'].'">
          <input type="hidden" name="sale_no" value="'.$detail['sale_no'].'">
          <input type="hidden" name="out_number[]" value="'.$detail['out_number'].'">
          <input type="hidden" name="pid" value="'.$detail['product_id'].'">
           </td>';
          $tr_str .= "<td><input type='text' name='sale_title[]' class='span5' value='".$detail['sale_title']."'>";
          if(!empty($detail['options']))
             $tr_str .= "<input type='text' name='options[]' class='span5' value='".$detail['options']."'></td>";
          else
              $tr_str .="<input type='hidden' name='options[]' value=''></td>";
          $tr_str .= "<td></td>"; //规格
          $tr_str .= "<td>--</td>";  //商品编号
          $tr_str .= "<td>--</td>"; //商品名称
          $tr_str .= "<td>--</td>";   //库位
          $tr_str .= "<td><input type='text' name='price[]' class='span1' value='".$detail['price']."'></td>";   //价格
          $tr_str .= "<td><input type='text' name='number[]' class='span1' value='".$detail['number']."'></td>";  //商品编号 //数量
          $tr_str .= "<td>".getProductUnit($detail['product_id'])."</td>";   //单位
          $tr_str .= "<td>--</td>";   //小计
          $tr_str .= "<td>--</td>";   //库存
          $tr_str .= "<td><input type='hidden' name='jumpUrl' value='".__APP__."/Sale/edit/id/".$detail['sale_id']."'><input type='submit' value='新增' class='btn'> </td>";
          $tr_str .=" <td class='span1'><a href='javascript:void(0)' class='btn' alt='删除' onclick='removerow(this);'>删除</a></td>";
          $tr_str .="<td></td></form></tr>";

          $data['sale_detail'] = $tr_str ;
          $this->ajaxReturn($data, '', 1);
      }else{
        $this->ajaxReturn(null, '订单商品明细无法获取！', 0);
      }
      
    }

    //复制对应订单详情中的商品
    public function copy_detail()
    { $sale = M('Sale')->getById($_POST['sale_id']);
      $_POST['customer_id'] = $sale['customer_id'];
      $_POST['order_source_id'] = $sale['order_source_id'];
      if($_POST['order_source_id'] != 3)
          $goods_id = getMyGoodsIdJw($_POST['out_number']['0'],$_POST['sale_title']['0'] );
      else //淘宝订单
         $goods_id = getMyGoodsId($_POST['out_number']['0'],$_POST['options']['0'] );
      if($goods_id > 0)
        $_POST['product_id']['0'] = $goods_id;
      else
        $_POST['product_id']['0'] = 0 ;

      if($_POST['product_id']['0'] == 0 )
          $this->error('商品编号不正确，需重新修改颜色，度数 或 非眼镜类产品无法使用复制功能！',false,5);
      else if( $goods_id == $_POST['pid'] )
          $this->error('请勿添加重复产品！',false,5);
      $this->insert();
    }

    //删除
    public function foreverdelete($field='name') {
        //删除指定记录
        $name=$this->getActionName();
        $model = D ($name);
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $id = $_REQUEST [$pk];
            if (isset ( $id )) {
                $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
                $old = $model->where($condition)->findAll();
                $mod_field = getModelName($id, $name, $field);
                //对应订单的配货状态
                $sale_pstatus = M('Sale')->where('id = '.getModelName($id,'Sale_detail','sale_id'))->getField('prepare_status');
                $p_id = getModelName($id,'Sale_detail','sale_id');//TODO 暂适用于单个删除的情况
                if (false !== $model->where($condition)->delete()) {
                    $new = array();
                    $msg = '删除 ' . $name . ': ' . $mod_field . ' (编号：' . $id . ')';
                    A('Action')->writeLog($msg, '删除', $name,$id, $old,$new);
                    
                    
                    //如果修改了价格，则同时更新total
                    $total = M('Sale_detail')->where('sale_id = '.$p_id)->sum('total');
                    M('Sale')->where('id = '.$p_id)->setField('total',$total);
                   

                    //TODO 现仅适用于单个删除情况
                    //update sum_number
                     $total = M('Sale_detail')->where('sale_id = '.$p_id)->sum('number');
                     M('Sale')->where('id = '.$p_id)->setField('sum_number',$total);

                    
                    
                    //通知仓库配货
                    if( $sale_pstatus == 1 || $sale_pstatus == 2){
                        //修复配货状态
                        $this->reback_toshipping($p_id);
                        //自动创建客服备注
                        $content = "删除了一条商品明细,需要重新打印配货单";
                        //A('Message')->write_message($p_id,2,$content,$_SESSION[C('USER_AUTH_KEY')]);
                        $this->success('修改成功。<br/><br/><font color="red">该单正在配货中，请通知仓库调整！</font>',false,10);
                    }else
                        $this->success('删除成功！');
                } else {
                    $this->error ('删除失败！');
                }
            } else {
                $this->error ( '非法操作' );
            }
        }
        $this->forward ();
    }

    //检查对应订单内的商品是否是缺货状态,如果都不缺货,则更改订单配货状态为:货齐待打印;如果全部订单内的商品明细皆为货齐已配货状态,则置为已配货.
    private function reback_toshipping($sale_id){
        $sdetails = M('Sale_detail')->where('sale_id = '.$sale_id)->field('prepare_status')->findAll();
        foreach($sdetails as $k=>$v){
            if($v['prepare_status'] == 2)
                return;
            if($v['prepare_status'] == 0){
                M('Sale')->where('id = '.$sale_id)->setField('prepare_status',0);//置为货齐待打印
                return;
            }
        }
       M('Sale')->where('id = '.$sale_id)->setField('prepare_status',1); //置为货齐已配货
    }

}
?>
